package com.swak.vertx.protocol.http.converter;

import com.swak.vertx.transport.multipart.Response;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerResponse;

/**
 * 自定义响应
 *
 * @author: lifeng
 * @date: 2020/3/29 19:21
 */
public class ResponseMessageConverter implements HttpMessageConverter {

	/**
	 * 只处理自定义响应
	 */
	@Override
	public boolean canWrite(Class<?> clazz) {
		return Response.class == clazz;
	}

	/**
	 * 输出数据
	 */
	@Override
	public void write(Object t, HttpServerResponse response) {
		Response out = (Response) t;
		response.setStatusCode(out.getStatus());
		if (out.getHeaders() != null && !out.getHeaders().isEmpty()) {
			out.getHeaders().forEach((key, value) -> {
				response.putHeader(key, value);
			});
		}
		if (out.getCookie() != null) {
			response.addCookie(out.getCookie());
		}
		if (out.getData() != null) {
			response.end(Buffer.buffer(out.getData()));
		} else {
			response.end();
		}
	}
}